package gttp.nspa.server.dao;

import gttp.nspa.shared.om.IEntity;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

public class DAJ<E extends IEntity> {

    private String         jsonFile;
    private Map<String, E> map;
    private List<E>        list;

    public DAJ(String jsonFile) {
        this.jsonFile = jsonFile;
        load();
    }

    private void load() {
        Map newMap = new HashMap();
        Gson gson = new GsonBuilder().create();
        try {
            InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(jsonFile));
            try {
                List<E> newList = gson.fromJson(reader, new TypeToken<List<E>>() {}.getType());
                for (E obj : newList) {
                    newMap.put(obj.getCode(), obj);
                }
                map = newMap;
                list = newList;
            } finally {
                reader.close();
            }
        } catch (JsonSyntaxException | JsonIOException | IOException e) {
            e.printStackTrace();
        }
    }

    public E get(String code) {
        return map.get(code);
    }

    public List<E> list() {
        return list;
    }
}
